﻿// =================================================================================================
//   CDlgInspect class
//
// Copyright © InnovMetric Software Inc. 2018 All Rights Reserved
// -------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;

using LaserRadar2;


namespace LaserRadar
{

    // =================================================================================================
    //   Class implementing the main plug-in dialog in Inspector mode.
    // -------------------------------------------------------------------------------------------------
    internal partial class CDlgInspect : Form
    {
        private const string SCAN_TYPE_SURFACE = "Surface";
        private const string SCAN_TYPE_BOUNDARY = "Surface and Boundary";
        private const string SCAN_TYPE_SHARP_EDGE = "Sharp Edge";

        //新增
        private const string SCAN_TYPE_OBJECT = "Object";



        private const string DATA_TYPE_POLYGONAL = "Polygonal Model";
        private const string DATA_TYPE_POINT_CLOUD = "Point Cloud from Mesh";

        //private IM.CIMHost m_host;
        //public CReceiver m_receiver;
        //private CSettings m_settings;
        public DeviceRadar m_Radar;
        private List<string> m_profileCmdArgNames;
        private bool m_synchronizingProfiles = false;


        List<pathPoint> m_path = new List<pathPoint>();
        static char[] chDelimiter = new char[] { ' ', '\t', ';', ',', ':', '+' };
        //private bool m_passIsStarted = false;
        // Int instead of bool to use with Interlocked.
        //private int m_endScanRequested = 0;

        #region window
        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
        public delegate bool EnumChildWindow(IntPtr WindowHandle, string num);
        [DllImport("User32.dll")]
        public static extern int EnumChildWindows(IntPtr WinHandle, EnumChildWindow ecw, string name);
        [DllImport("User32.dll")]
        public static extern int GetWindowText(IntPtr WinHandle, StringBuilder Title, int size);

        [DllImport("MatlabDLL2.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern int sectionWithPlane(double[] section_data, double[] normal, double[] locat, string filename);

        [DllImport("MatlabDLL2.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern int fnMatlabDLL2();

        [DllImport("MatlabDLL2.dll", CallingConvention = CallingConvention.Cdecl)]
        private static extern int circle_compute(int num, double[] inputdata, double[] sigma, double[] center, double[] radius, double[] normal);

        /// <summary>
        /// 获取指定窗口（或控件）在屏幕中的位置信息 （左边界，上边界，右边界，下边界）
        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="lpRect">LPRECT矩形结构的长指针,数据存储使用struct类型</param>
        /// <returns>获取成功返回非0值,失败返回0</returns>
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetWindowRect(IntPtr hWnd, ref RECT_INFO lpRect);

        // <summary>
        /// 矩形范围信息（结构体）
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct RECT_INFO
        {
            /// <summary>
            /// 当前矩形范围的最左边界
            /// </summary>
            public int Left;
            /// <summary>
            /// 当前矩形的最上边界
            /// </summary>
            public int Top;
            /// <summary>
            /// 当前矩形的最右边界
            /// </summary>
            public int Right;
            /// <summary>
            /// 当前矩形的最下边界
            /// </summary>
            public int Bottom;
        }
        #endregion

        // private Int64 pointId = 0;

        // =================================================================================================
        //   Ask the application to return the current scan type and convert the answer from the MSCL
        // string to the COM enum.
        //
        // Return : The current scan type.
        // -------------------------------------------------------------------------------------------------
        //private IMPluginLib.EScanTypes IMIScanTypeGet()
        //{
        //    string scanType = m_host.ValueStrGet(Consts.CMD_SCAN_TYPE + Consts.CMD_GET_SUFFIX, "", false);

        //    if (scanType == SCAN_TYPE_SHARP_EDGE)
        //    {
        //        return IMPluginLib.EScanTypes.E_SCAN_TYPE_SHARP_EDGE;
        //    }
        //    else if (scanType == SCAN_TYPE_BOUNDARY)
        //    {
        //        return IMPluginLib.EScanTypes.E_SCAN_TYPE_SURFACE_AND_BOUNDARY;
        //    }

        //    return IMPluginLib.EScanTypes.E_SCAN_TYPE_SURFACE;
        //}

        // =================================================================================================
        //   Constructor used only by the designer.
        // -------------------------------------------------------------------------------------------------
        public CDlgInspect()
        {
            InitializeComponent();
        }

        // =================================================================================================
        //   Real constructor used when we create the dialog at runtime.
        //
        // Parameter : receiver_ : Access to the receiver.
        // -------------------------------------------------------------------------------------------------
        //public CDlgInspect(CReceiver receiver_)
        //{
        //    InitializeComponent();

        //    m_receiver = receiver_;
        //    m_host = m_receiver.Host;
        //    m_settings = m_receiver.Settings;
        //    DialogUpdate();
        //    m_receiver.EnableRealTimeMeshing(m_settings.IMIRealTimeMeshing);
        //    m_receiver.StateChanged += ReceiverStateChanged;
        //}

        // =================================================================================================
        //   Update the status of a pair of combobox/textbox controlling the name of the data object where
        // scanlines are stored. Since there are 2 pairs (surface and boundary), the controls are passed as
        // parameters.
        //
        // Parameter : name_     : The textbox control to update.
        // Parameter : objects_  : The combobox control to update.
        // Parameter : scanType_ : The scan type to use to retrieve the list of names.
        // -------------------------------------------------------------------------------------------------
        //private void DataObjectsUpdate(TextBox name_, ComboBox objects_, IMPluginLib.EScanTypes scanType_)
        //{
        //    List<string> names;

        //    // Get the application Data Object names
        //    string currentChoice = m_receiver.ScanningObjectsGet(scanType_, out names);

        //    names.Insert(0, "(Create New)");

        //    IM.Utils.ComboAndListSynchronize(objects_, names, currentChoice, 0);

        //    name_.Enabled = objects_.SelectedIndex == 0;

        //    name_.Text = currentChoice;
        //}

        // =================================================================================================
        //   Update the enabled state of all controls according to current status.
        // -------------------------------------------------------------------------------------------------
        private void EnableScanControls()
        {

            //获取扫描状态
            bool enable = true;
            if (m_Radar != null)
            {
               // enable = !m_Radar.IsScanning;// !m_receiver.IsScanning;
            }

            this.Invoke(new EventHandler(delegate
            {
                m_rbSurface.Enabled = enable;
                m_rbSurfaceAndBoundary.Enabled = enable;
                m_rbSharpEdge.Enabled = enable;

                bool useRTM = m_cbRTQM.Checked;
                bool isSharpEdge = m_rbSharpEdge.Checked;
                bool isCreatingNewDataObject = m_cbSurface.SelectedIndex == 0;

                m_cbSurface.Enabled = enable && !isSharpEdge;
                //m_tbSurfaceName.Enabled = enable && !isSharpEdge && isCreatingNewDataObject;
                m_tbSurfaceName.Enabled = true;
                m_cbRTQM.Enabled = enable && !isSharpEdge && isCreatingNewDataObject;

                m_lbDataType.Enabled = enable && !isSharpEdge && useRTM;
                m_rbPointCloud.Enabled = enable && !isSharpEdge && useRTM;
                m_rbPolygonal.Enabled = enable && !isSharpEdge && useRTM;

                m_cbTestMode.Enabled = enable;
                m_pbOptions.Enabled = enable;
                m_pbClose.Enabled = enable;

                bool isBoundary = m_rbSurfaceAndBoundary.Checked;
                isCreatingNewDataObject = m_cbBoundary.SelectedIndex == 0;
                m_cbBoundary.Enabled = enable && (isBoundary || isSharpEdge);
                m_tbBoundaryName.Enabled = enable && (isBoundary || isSharpEdge) && isCreatingNewDataObject;

                m_cbComparison.Enabled = enable && !isSharpEdge && !useRTM;

                bool clippingPlane = m_cbClippingPlane.Checked;
                m_cbClippingPlane.Enabled = enable && !isSharpEdge;
                m_tbClippingPlane.Enabled = enable && !isSharpEdge && clippingPlane;
                m_pbClippingPlane.Enabled = enable && !isSharpEdge && clippingPlane;

                m_lbProfile.Enabled = enable;
                m_cbProfile.Enabled = enable;
                m_pbSave.Enabled = enable;
                m_pbDeleteProfile.Enabled = enable;

                if (enable)
                {
                    //m_pbStart.Text = "Start Scan";
                    m_pbStart.Text = "扫描";
                }
                else
                {
                    //m_pbStart.Text = "End Scan";
                    m_pbStart.Text = "停止";
                }
            }));
        }

        // =================================================================================================
        //   Event-handler called when the Clipping plane checkbox changes. The new value is sent to the
        // application and the dialog is updated.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void cbClippingPlaneCheckedChanged(object sender, EventArgs e)
        {
            //m_host.ValueSet(Consts.CMD_CLIPPING_PLANE, m_cbClippingPlane.Checked, true, false);

            EnableScanControls();
        }

        // =================================================================================================
        //   Event-handler called when the Real-time comparison checkbox changes. The new value is written
        // in the corresponding setting.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void cbComparisonCheckedChanged(object sender, EventArgs e)
        {
           // m_settings.IMIRealTimeInspection = m_cbComparison.Checked;
        }

        // =================================================================================================
        //   Event-handler called when the selection in the scanning profile combobox changes. The new
        // selection is sent to the application.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void cbProfileSelectedIndexChanged(object sender, EventArgs e)
        {
            // When synchronizing the combobox with the profile list reported by the application,
            // the selected index may change more than once. We want to avoid calling the command
            // with temporary selections.
            if (!m_synchronizingProfiles)
            {
                int selection = m_cbProfile.SelectedIndex;

                if ((selection >= 0) && (selection < m_profileCmdArgNames.Count))
                {
                  //  m_host.ExecuteCommand(IM.Utils.CommandBuild("DIGITIZE DEVICE SCAN PROFILE",
                    //                                              IM.Utils.Quote(m_profileCmdArgNames[selection])),
                     //                      true, true, true);
                }
                else
                {
                    System.Diagnostics.Debug.Assert(false);
                }
            }
        }

        // =================================================================================================
        //   Event-handler called when the Real-time quality meshing checkbox changes. The new value is
        // sent to the receiver.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void cbRTQMCheckedChanged(object sender, EventArgs e)
        {
            //m_receiver.EnableRealTimeMeshing(m_cbRTQM.Checked);
            m_cbComparison.Checked = false;
        }

        // =================================================================================================
        //   Event-handler called when the selection in the Boundary object name combobox changes.
        // If the selection is "Create new" we make sure the name used is unique and the textbox is enabled.
        // Otherwise we set the name in the application to the current selection and disable the textbox. 
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void cbBoundarySelectedIndexChanged(object sender, EventArgs e)
        {
            string name;

            if (m_cbBoundary.SelectedIndex == 0)
            {
                m_tbBoundaryName.Enabled = true;

               // name = m_host.ValueStrGet("CONFIG MODIFY DEFAULT_NAME BOUNDARY_SCAN GET", "", false);
               // name = m_host.ObtainUniqueName(name);
            }
            else if (m_cbBoundary.SelectedItem != null)
            {
                m_tbBoundaryName.Enabled = false;

                name = m_cbBoundary.SelectedItem.ToString();
            }
            else
            {
                return;
            }

           // m_host.ExecuteCommand(IM.Utils.CommandBuild(Consts.CMD_SCAN_BOUNDARY_OBJECT_NAME, IM.Utils.Quote(name)), true, false, true);
        }

        // =================================================================================================
        //   Event-handler called when the selection in the Surface object name combobox changes.
        // If the selection is "Create new" we make sure the name used is unique and the textbox is enabled.
        // Otherwise we set the name in the application to the current selection and disable the textbox. 
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void cbSurfaceSelectedIndexChanged(object sender, EventArgs e)
        {
            string name;

            if (m_cbSurface.SelectedIndex == 0)
            {
                m_tbSurfaceName.Enabled = true;

                //name = m_host.ValueStrGet("CONFIG MODIFY DEFAULT_NAME SURFACE_SCAN GET", "", false);
                //name = m_host.ObtainUniqueName(name);
            }
            else if (m_cbSurface.SelectedItem != null)
            {
                //m_tbSurfaceName.Enabled = false;
                m_tbSurfaceName.Enabled = true; ;
                name = m_cbSurface.SelectedItem.ToString();
            }
            else
            {
                return;
            }

            //m_host.ExecuteCommand(IM.Utils.CommandBuild(Consts.CMD_SCAN_SURFACE_OBJECT_NAME, IM.Utils.Quote(name)), true, false, true);
        }

        // =================================================================================================
        //   Event-handler called when the Test mode checkbox changes. We write the current value in the
        // corresponding setting.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void cbTestModeCheckedChanged(object sender, EventArgs e)
        {
           // m_settings.TestMode = m_cbTestMode.Checked;
        }

        // =================================================================================================
        //   Event-handler called when the Clipping plane push button is clicked. We call the command to
        // define the clipping plane which will show an application dialog.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void pbClippingPlaneClick(object sender, EventArgs e)
        {
            //m_host.ExecuteCommand("DIGITIZE CLIPPING_PLANE DEFINE SHOW_WINDOW", true, true, true);
        }

        // =================================================================================================
        //   Event-handler called when the Close push button is clicked. Simply closes the window.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void pbCloseClick(object sender, EventArgs e)
        {
           // this.timer_readTemperature.Stop();
            Close();
        }

        // =================================================================================================
        //   Event-handler called when the Delete (profile) push button is clicked. We call the command
        // that performs the deletion (the application will display a confirmation message).
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void pbDeleteProfileClick(object sender, EventArgs e)
        {
            int selection = m_cbProfile.SelectedIndex;

            if ((selection >= 0) && (selection < m_profileCmdArgNames.Count))
            {
               // m_host.ExecuteCommand(IM.Utils.CommandBuild("DIGITIZE DEVICE SCAN PROFILE DELETE",
               //                       IM.Utils.Quote(m_profileCmdArgNames[selection])),
                //                       true, true, true);
            }
            else
            {
                System.Diagnostics.Debug.Assert(false);
            }
        }

        // =================================================================================================
        //   Event-handler called when the Options push button is clicked. We simply show the Options
        // dialog box.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void pbOptionsClick(object sender, EventArgs e)
        {
            //CDlgOptions dialog = new CDlgOptions(m_host);

            //dialog.ShowDialog(this);
        }

        // =================================================================================================
        //   Event-handler called when the Save (profile) push button is clicked. Show the save dialog.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void pbSaveClick(object sender, EventArgs e)
        {
           // CDlgSaveAsProfile dialog = new CDlgSaveAsProfile(m_receiver);

            //dialog.ShowDialog(this);
        }

        // =================================================================================================
        //   Event-handler called when the Start/End Scan push button is clicked. If scanning is started
        // the command to end the scan will be called. Otherwise the command to start scanning will be
        // called.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void pbStartClick(object sender, EventArgs e)
        {
            Debug.WriteLine("设备是否扫描中：" + m_Radar.IsScanning.ToString());
            ///停止扫描
            if (m_Radar.IsScanning)
            {
                try
                {
                    m_Radar.IsScanning = false;
                    this.Invoke(new EventHandler(delegate
                    {


                        //m_receiver.ScanEndRequest();
                        switch (comboBox_method.SelectedIndex)
                        {
                            //区域扫描
                            case 0:
                                m_Radar.MoveStop();
                                m_Radar.PolygonScanEnd();
                                break;
                            //单点扫描
                            case 1:
                                m_Radar.MoveStop();
                                m_Radar.StopScan();
                                break;
                            //多边形扫描
                            case 2:
                                m_Radar.MoveStop();
                                //m_Radar.PolygonScanEnd();
                                break;
                            //测孔扫描
                            case 3:

                                break;
                            default:

                                return;
                        }
                    }));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
                //m_cbSurface.SelectedIndex = 0;
            }
            ///开始扫描
            else
            {
                this.curPtsKey = this.m_tbSurfaceName.Text;

                //if (!FeatureManager.addPointCloud(this.curPtsKey))
                //{
                //    MessageBox.Show("已存在同名数据，请修改点云名称");
                //    return;
                //}
                //if (!this.MdiParent.m_viewFrom.InitCloudNode(this.curPtsKey))
                //    return;
                //m_host.ExecuteCommand("DIGITIZE DEVICE SCAN START", true, true, false);
                //pointId = 0;
                // m_receiver.m_passStarted = true;
                //m_receiver.m_stub.m_passIsStarted = false;
                ////曲面扫描
                if (m_rbSurface.Checked)
                {

                    double speed = Convert.ToDouble(this.textBox_ScanSpeed.Text); ;
                    //string name = m_tbSurfaceName.Text;
                    //m_host.ExecuteCommand(IM.Utils.CommandBuild(Consts.CMD_SCAN_SURFACE_OBJECT_NAME, IM.Utils.Quote(name)), true, false, true);
                    switch (comboBox_method.SelectedIndex)
                    {
                        //区域扫描
                        case 0:
                            if (m_Radar.m_Path.Count < 3)
                            {
                                MessageBox.Show("测量路径点小于3，请重新设置");
                                //m_receiver.m_passStarted = false;
                                //m_receiver.m_stub.m_passIsStarted = true;
                                //m_receiver.ScanEndRequest();
                                return;
                            }
                            m_Radar.m_ScanOrignData = new StreamWriter("区域原始数据.txt");
                            m_Radar.SendScanMeas += new ScanMeasureCallback(ReceivedScanMeasureCallBack);
                            Task scanRectTask = new Task(() =>
                            {
                                m_Radar.PolygonScanProcess(speed);
                            });
                            scanRectTask.Start();

                            break;
                        //单点扫描
                        case 1:
                            m_Radar.m_Path = m_path;
                            if (m_Radar.m_Path.Count < 3)
                            {
                                MessageBox.Show("测量路径点小于3，请重新设置");
                                return;
                            }
                            m_Radar.SendSingleMeas += new SingleMeasureCallback(ReceivedSingeMeasureCallBack);
                            double xstep = Convert.ToDouble(this.textBox_xstep.Text);
                            double ystep = Convert.ToDouble(this.textBox_ystep.Text);
                            m_Radar.StartSingleScan(xstep, ystep, speed);
                            break;
                        //多边形扫描
                        case 2:

                            if (m_Radar.m_Path.Count < 3)
                            {
                                MessageBox.Show("测量路径点小于3，请重新设置");
                                // m_receiver.m_passStarted = false;
                                //m_receiver.m_stub.m_passIsStarted = true;
                                //m_receiver.ScanEndRequest();
                                return;
                            }
                            m_Radar.SendScanMeas += new ScanMeasureCallback(ReceivedScanMeasureCallBack);
                            m_Radar.IsScanning = true;
                            Task scanPolygonTask = new Task(() =>
                            {
                                m_Radar.PolygonScanProcess(speed);
                            });
                            scanPolygonTask.Start();
                            break;
                        //扫描球
                        case 3:
                            //m_path = m_Radar.generateSphereScanPath();
                            //m_Radar.m_Path = m_path;
                            //if (m_Radar.m_Path.Count < 3)
                            //{
                            //    MessageBox.Show("测量路径点小于3，请重新设置");
                            //    return;
                            //}
                            //m_Radar.SendSingleMeas += new SingleMeasureCallback(ReceivedSingeMeasureCallBack);
                            //double xstep2 = Convert.ToDouble(this.textBox_xstep.Text);
                            //double ystep2 = Convert.ToDouble(this.textBox_ystep.Text);
                            //m_Radar.StartSingleScan(xstep2, ystep2, speed);
                            break;
                        default:
                            MessageBox.Show("测量方式不存在");
                            return;
                    }
                }
                //特征扫描
                if (m_rbFeature.Checked)
                {
                    int count = Convert.ToInt32(this.textBox_count.Text);
                    int turns = Convert.ToInt32(this.textBox_turns.Text);
                    double radius = Convert.ToDouble(this.textBox_radius.Text);
                    double speed = Convert.ToDouble(this.textBox_featureSpeed.Text);
                    var currPos = m_Radar.GetOneData();
                    double currentA = currPos.a;
                    double currentB = currPos.b;
                    double targetA = currPos.a;
                    double targetB = currPos.b;
                    double currentDis = currPos.dis;

                    ////测孔扫描
                    if (comboBox_featureMethod.SelectedIndex == 0)
                    {
                        Task circleScanTask = new Task(() =>
                        {
                            string time = /*DateTime.Now.Date.ToString()+*/ DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00");
                            m_Radar.m_ScanOrignData = new StreamWriter("测孔原始数据" + time + ".csv");
                            m_Radar.SendScanMeas += new ScanMeasureCallback(ReceivedScanMeasureCallBack);
                            m_Radar.CircleScanMove(count, radius, currentA, currentB, targetA, targetB, speed);

                            //清空特征扫描记录的数据
                            //m_receiver.m_stub.m_ScanData.Clear();
                        });
                        circleScanTask.Start();
                    }
                    else if (comboBox_featureMethod.SelectedIndex == 1)
                    {
                        Task spinScanTask = new Task(() =>
                        {
                            m_Radar.SendScanMeas += new ScanMeasureCallback(ReceivedScanMeasureCallBack);
                            m_Radar.IsScanning = true;
                            m_Radar.SpinScanMove(count, turns, radius, currentA, currentB, targetA, targetB, speed);

                            //清空特征扫描记录的数据
                            //m_receiver.m_stub.m_ScanData.Clear();
                        });
                        spinScanTask.Start();
                    }
                    ///交叉扫描特征球
                    else if (comboBox_featureMethod.SelectedIndex == 2)
                    {
                        Task sphereScanTask = new Task(() =>
                        {
                            double deltaA = Math.Atan(19.05 / (19.05 + currentDis)) * 180 / Math.PI;
                            double deltaB = Math.Atan(19.05 / (19.05 + currentDis)) * 180 / Math.PI / 2;
                            m_Radar.SendScanMeas += new ScanMeasureCallback(ReceivedScanMeasureCallBack);
                            m_Radar.CircleScanMove(10, deltaA / 2, currentA, currentB, targetA, targetB, 0.2);
                        });
                        sphereScanTask.Start();
                    }
                }
            }

            EnableScanControls();
        }

        // =================================================================================================
        //   Event-handler called when the one of the RTQM data type radio buttons is selected. We call
        // the command to inform the application of the new selection.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void rbPolygonalCheckedChanged(object sender, EventArgs e)
        {
            string type = DATA_TYPE_POINT_CLOUD;

            if (m_rbPolygonal.Checked)
            {
                type = DATA_TYPE_POLYGONAL;
            }

            //m_host.ExecuteCommand(IM.Utils.CommandBuild(Consts.CMD_RTQM_DATA_TYPE, IM.Utils.Quote(type)), true, false, true);
        }

        // =================================================================================================
        //   Event-handler called when one of the Scan Type radio buttons is selected. We inform the
        // application of the new value and update the controls accordingly.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void rbScanTypeCheckedChanged(object sender, EventArgs e)
        {
            string scanTypeStr = "";

            if (m_rbSurface.Checked)
            {
                scanTypeStr = SCAN_TYPE_SURFACE;
                groupBox_devicePara.Visible = true;
                groupBox_featurePara.Visible = false;
            }
            //else if (m_rbSurfaceAndBoundary.Checked)
            //{
            //    scanTypeStr = SCAN_TYPE_BOUNDARY;
            //}
            //else if (m_rbSharpEdge.Checked)
            //{
            //    scanTypeStr = SCAN_TYPE_SHARP_EDGE;
            //}          
            else if (m_rbFeature.Checked)
            {
                scanTypeStr = SCAN_TYPE_SURFACE;
                groupBox_devicePara.Visible = false;
                groupBox_featurePara.Visible = true;
            }
            else
            {
                System.Diagnostics.Debug.Assert(false);
            }
           // if( !m_receiver.IsScanning)
           //     m_host.ValueSet(Consts.CMD_SCAN_TYPE, IM.Utils.Quote(scanTypeStr), true, false);

            EnableScanControls();
        }

        // =================================================================================================
        //   Event-handler called when the Boundary textbox loses focus. We send the object name to the
        // application.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void tbBoundaryNameLeave(object sender, EventArgs e)
        {
            string name = m_tbBoundaryName.Text;
           // name = m_host.ObtainUniqueName(name);
           // m_host.ExecuteCommand(IM.Utils.CommandBuild(Consts.CMD_SCAN_BOUNDARY_OBJECT_NAME, IM.Utils.Quote(name)), true, false, true);
        }

        // =================================================================================================
        //   Event-handler called when the Surface textbox loses focus. We send the object name to the
        // application.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void tbSurfaceNameLeave(object sender, EventArgs e)
        {
            string name = m_tbSurfaceName.Text;
          //  name = m_host.ObtainUniqueName(name);
           // m_host.ExecuteCommand(IM.Utils.CommandBuild(Consts.CMD_SCAN_SURFACE_OBJECT_NAME, IM.Utils.Quote(name)), true, false, true);
        }

        // =================================================================================================
        //   Event-handler called when the window is moved. The new position is stored in settings.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void Moved(object sender, EventArgs e)
        {
            // We must update the settings when the form is moved only once it is visible. Otherwise
            // we will modify the setting before "Showned" is called and the initial position is set.
            //if (Visible)
            //{
            //  //  m_settings.IMIWindowPositionX = Left;
            ////    m_settings.IMIWindowPositionY = Top;
            //}
        }

        // =================================================================================================
        //   Event-handler called when something happens in the receiver that may require refreshing the
        // dialog.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void ReceiverStateChanged(object sender, EventArgs e)
        {
            EnableScanControls();
        }

        // =================================================================================================
        //   Event-handler called when the window is first showned. The window is moved to its last saved
        // position.
        //
        // Parameter : sender : Not used
        // Parameter : e      : Not used
        // -------------------------------------------------------------------------------------------------
        private void Showned(object sender, EventArgs e)
        {
            //DesktopLocation = new Point(m_settings.IMIWindowPositionX,
            //                             m_settings.IMIWindowPositionY);
        }

        // =================================================================================================
        //   Updates the dialog
        // -------------------------------------------------------------------------------------------------
        public void DialogUpdate()
        {
            //switch (IMIScanTypeGet())
            //{
            //    case IMPluginLib.EScanTypes.E_SCAN_TYPE_SURFACE:
            //        m_rbSurface.Checked = true;
            //        break;
            //    case IMPluginLib.EScanTypes.E_SCAN_TYPE_SURFACE_AND_BOUNDARY:
            //        m_rbSurfaceAndBoundary.Checked = true;
            //        break;
            //    case IMPluginLib.EScanTypes.E_SCAN_TYPE_SHARP_EDGE:
            //        m_rbSharpEdge.Checked = true;
            //        break;
            //    default:
            //        // Scan type not suppported by this example.
            //        System.Diagnostics.Debug.Assert(false);
            //        break;
            //}

            //// Get RTM activation state from the application because it may have changed
            //bool? useRTM = m_host.ValueBoolGet(Consts.CMD_DIGITIZE_LINESCAN_SURFACE_RTQM_GET, false);
            //if (useRTM.HasValue)
            //{

            //    m_cbRTQM.Checked = useRTM.Value;
            //    m_settings.IMIRealTimeMeshing = useRTM.Value;
            //}
            //bool? useclippingPlane = m_host.ValueBoolGet(Consts.CMD_CLIPPING_PLANE + Consts.CMD_GET_SUFFIX, false).Value;
            //if (useclippingPlane.HasValue)
            //{
            //    m_cbClippingPlane.Checked = useclippingPlane.Value;
            //}
            //string clippingPlaneDateTime = "Undefined";
            //bool? isClippingPlaneDefined = m_host.ValueBoolGet("DIGITIZE CLIPPING_PLANE DEFINED GET", false);
            //if (isClippingPlaneDefined.HasValue && isClippingPlaneDefined.Value)
            //{
            //    clippingPlaneDateTime = m_host.ValueDateTimeGet("DIGITIZE CLIPPING_PLANE DEFINED DATE_TIME GET", false);
            //}
            //m_tbClippingPlane.Text = clippingPlaneDateTime;

            //string rtqmDataType = m_host.ValueStrGet(Consts.CMD_RTQM_DATA_TYPE + Consts.CMD_GET_SUFFIX, "", false);
            //bool isPolModel = rtqmDataType == DATA_TYPE_POLYGONAL;
            //m_rbPointCloud.Checked = !isPolModel;
            //m_rbPolygonal.Checked = isPolModel;

            //DataObjectsUpdate(m_tbSurfaceName, m_cbSurface, IMPluginLib.EScanTypes.E_SCAN_TYPE_SURFACE);
            //DataObjectsUpdate(m_tbBoundaryName, m_cbBoundary, IMPluginLib.EScanTypes.E_SCAN_TYPE_SHARP_EDGE);

            //m_cbComparison.Checked = m_settings.IMIRealTimeInspection;
            //m_cbTestMode.Checked = m_settings.TestMode;

            EnableScanControls();
        }

        // =================================================================================================
        //   Update the state of "scanning profiles" related controls after a change.
        // -------------------------------------------------------------------------------------------------
        public void ProfilesControlUpdate()
        {
            List<string> profileDisplayNames;
            List<string> profileAdditionalInfos;
            string currentProfile;

            //m_receiver.ScanningProfilesGet(out m_profileCmdArgNames,
            //                                out profileDisplayNames,
            //                                out profileAdditionalInfos,
             //                               out currentProfile);

            //if (m_profileCmdArgNames.Count != profileDisplayNames.Count)
            //{
            //    System.Diagnostics.Debug.Assert(false);
            //    return;
            //}

            //List<string> items = new List<string>();

            //for (int i = 0; i < m_profileCmdArgNames.Count; ++i)
            //{
            //    if (profileDisplayNames[i].Length > 0)
            //    {
            //        items.Add(profileDisplayNames[i]);
            //    }
            //    else
            //    {
            //        items.Add(m_profileCmdArgNames[i]);
            //    }
            //}

            //try
            //{
            //    m_synchronizingProfiles = true;
            //    IM.Utils.ComboAndListSynchronize(m_cbProfile, items, currentProfile, -1);
            //}
            //finally
            //{
            //    m_synchronizingProfiles = false;
            //}

            EnableScanControls();
        }

        private void CDlgInspect_Load(object sender, EventArgs e)
        {
            m_cbRTQM.Checked = false;
            m_cbComparison.Checked = true;
            m_rbSurface.Checked = true;
            comboBox_method.SelectedIndex = 0;
            comboBox_featureMethod.SelectedIndex = 0;
            
        }

        private void button_controlPanel_Click(object sender, EventArgs e)
        {

            Form_ManualControl m_manualControl = new Form_ManualControl(m_Radar);
            Process[] procs = Process.GetProcessesByName("iminspect");
            IntPtr mainHwnd;

            foreach (var p in procs)
            {

                if (p.Id != 0)
                {

                    IntPtr hwnd = new IntPtr(0);
                    IntPtr EdithWnd = new IntPtr(0);

                    //从指定的主窗体查找子窗体
                    //IntPtr childHwnd = FindWindowEx(hwnd, EdithWnd, null, "Scan");

                    ///从所有桌面的窗体中查找FindWindowEx（0,0,null,name）;
                    IntPtr childHwnd = FindWindowEx(hwnd, EdithWnd, null, "扫描");
                    mainHwnd = childHwnd;
                    StringBuilder name = new StringBuilder();
                    GetWindowText(childHwnd, name, 100);
                    RECT_INFO rect = new RECT_INFO();
                    GetWindowRect(childHwnd, ref rect);
                    m_manualControl.Left = rect.Right;
                    m_manualControl.Top = rect.Top;
                }
            }
            System.Windows.Forms.IWin32Window owner = null;
            m_manualControl.Show(owner);

        }

        private void button_camera_Click(object sender, EventArgs e)
        {
            Form_Camera m_Cam = new Form_Camera();
            System.Windows.Forms.IWin32Window owner = null;
            m_Cam.Show(owner);
        }
        private bool Connect()
        {
            //int num = 1;
            //string ip = "192.168.10.200";
            //int port = 2345;
            //string ip_singal = "";
            //int port_singal = 0;
            m_Radar = new DeviceRadar();
            if (!m_Radar.ConnectToMain())
            {
                Debug.WriteLine("控制卡失败");
                return false;
            }
            if (!m_Radar.ConnectToSingal())
            {
                Debug.WriteLine("连接信号卡失败");
                return false;
            }
            if (!m_Radar.ConnectToMovecard())
            {
                Debug.WriteLine("运动卡失败");
                return false;
            }
            m_Radar.SendStateValue += new SendStateCallback(receicedDeviceStatus);
            m_Radar.ReadSensorData();
           // timer_readTemperature.Enabled = true;
            IsConnected = true;
            return true;
        }
        bool IsConnected = false;
        private void button_connect_Click(object sender, EventArgs e)
        {
            if (!IsConnected)
            {
                bool connectFlag = Connect();
                if (connectFlag)//
                {
                    //timer_readTemperature.Start();
                    timer_readTemperature.Enabled = true;
                    m_Radar.SendStateValue += new SendStateCallback(receicedDeviceStatus);
                    //m_Radar.sen += new SendStateCallback(receicedDeviceStatus);
                    toolStrip_deviceStatus.Text = "连接成功";
                    button_connect.Text = "断开";
                    //每次开机后需要先使能电机
                    Task powerOnTask = new Task(() =>
                    {
                        m_Radar.PowerOn();
                    });
                    powerOnTask.Start();
                    EnableDeviceControls();
                }
                else
                {
                    toolStrip_deviceStatus.Text = "连接失败";
                }
            }
            else
            {
                //Disconnect();
                button_connect.Text = "连接";
                toolStrip_deviceStatus.Text = "断开";
                EnableDeviceControls();
            }
        }

        public void receicedDeviceStatus(string message)
        {
            switch (message)
            {
                case "区域扫描完成":
                    m_Radar.SendScanMeas -= new ScanMeasureCallback(ReceivedScanMeasureCallBack);
                    if (m_Radar.m_ScanOrignData != null)
                        m_Radar.m_ScanOrignData.Close();
                    //var thread0 = new System.Threading.Thread(new System.Threading.ThreadStart(m_receiver.ScanEndRequest));
                    //thread0.SetApartmentState(System.Threading.ApartmentState.STA);
                    //thread0.Start();
                    //if (m_AGV != null)
                    //{
                    //    //m_AGV.isRadarScaning = false;
                    //    //m_AGV.currentComplete = false;
                    //}
                    break;
                case "孔扫描完成":
                    //this.MdiParent.m_viewFrom.deleteCallback();
                    m_Radar.SendScanMeas -= new ScanMeasureCallback(ReceivedScanMeasureCallBack);
                    if(m_Radar.m_ScanOrignData!=null)
                        m_Radar.m_ScanOrignData.Close();
                    //var thread1 = new System.Threading.Thread(new System.Threading.ThreadStart(m_receiver.ScanEndRequest));
                    //thread1.SetApartmentState(System.Threading.ApartmentState.STA);
                    //thread1.Start();

                    //从点云中识别孔

                    //var thread5 = new System.Threading.Thread(new System.Threading.ThreadStart(CreateCircleFormCloud));
                    //thread5.SetApartmentState(System.Threading.ApartmentState.STA);
                    //thread5.Start();


                    //新建一个测量名称
                    //this.Invoke(new EventHandler(delegate
                    //{
                    //    m_cbSurface.SelectedIndex = 0;
                    //}));
                    break;
                case "螺旋形扫描完成":
                    m_Radar.SendScanMeas -= new ScanMeasureCallback(ReceivedScanMeasureCallBack);

                    //var thread2 = new System.Threading.Thread(new System.Threading.ThreadStart(m_receiver.ScanEndRequest));
                    //thread2.SetApartmentState(System.Threading.ApartmentState.STA);
                    //thread2.Start();
                    //新建一个测量名称
                    //this.Invoke(new EventHandler(delegate
                    //{
                    //    m_cbSurface.SelectedIndex = 0;
                    //}));
                    break;
                case "多边形扫描完成":
                    m_Radar.SendScanMeas -= new ScanMeasureCallback(ReceivedScanMeasureCallBack);
                    if (m_Radar.m_ScanOrignData != null)
                        m_Radar.m_ScanOrignData.Close();

                    Task newtt = new Task(() =>
                    {
                        pbStartClick(new object(), new EventArgs());
                    });
                    newtt.Start();
                    //if (m_AGV != null)
                    //{
                    //    //m_AGV.isRadarScaning = false;
                    //}
                    //var thread3 = new System.Threading.Thread(new System.Threading.ThreadStart(m_receiver.ScanEndRequest));
                    //thread3.SetApartmentState(System.Threading.ApartmentState.STA);
                    //thread3.Start();

                    ////新建一个测量名称
                    //this.Invoke(new EventHandler(delegate
                    //{
                    //    m_cbSurface.SelectedIndex = 0;
                    //}));

                    break;
                case "方位指向完成":
                    //showFlagA_Lihgt = false;
                    //this.getScanData = false;
                    break;
                case "俯仰指向完成":
                    //showFlagB_Lihgt = false;
                    //this.getScanData = false;
                    break;
                case "单点扫描完成":
                    m_Radar.SendSingleMeas -= new SingleMeasureCallback(ReceivedSingeMeasureCallBack);
                    //var thread4 = new System.Threading.Thread(new System.Threading.ThreadStart(m_receiver.ScanEndRequest));
                    //thread4.SetApartmentState(System.Threading.ApartmentState.STA);
                    //thread4.Start();
                    break;
                case "连接已断开":
                    MessageBox.Show(message); ;
                    break;
                    
                default:
                    break;
            }
            //Debug.WriteLine("CDlgInspect:"+message);
            this.Invoke(new EventHandler(delegate
            {
                toolStrip_deviceStatus.Text = message;
            }));

        }
        public List<SAPoint> m_cloud = new List<SAPoint>();
        private Int64 pointId = 0;
        public List<double> m_ScanData = new List<double>();
        public string curPtsKey = null;
        //new public MainForm MdiParent { set; get; }
        public void ReceivedScanMeasureCallBack(double x, double y, double z)
        {
            pointId++;
            m_cloud.Add(new SAPoint(x,y,z));

            ///存储原始数据，用于特征计算
            m_ScanData.Add(x);
            m_ScanData.Add(y);
            m_ScanData.Add(z);

            if (pointId % 1000 == 0)
            {
                // send points
            }
            //MeasFeatures.Get_Instance().Get_FeatPointCloud(this.curPtsKey).cloudPoints.Add(new BasePoint(x, y, z));
            //this.MdiParent.m_viewFrom.AddPoints(x, y, z);
        }
        public void ReceivedSingeMeasureCallBack(double x, double y, double z)
        {
            m_cloud.Add(new SAPoint((float)x, (float)y, (float)z));
            string groupName = "Group";
            string name = "Pt" + pointId;
            //this.MdiParent.addSinglePoint(groupName, name, x, y, z);
        }
        private void button_initRadar_Click(object sender, EventArgs e)
        {
            if (m_Radar != null)
            {
                m_Radar.InitDevice();
            }
        }

        private void timer_readTemperature_Tick(object sender, EventArgs e)
        {
            if (m_Radar != null)
            {
                //m_Radar.ReadSensorData();
                //m_Radar.ReadCyberTemper();
            }
        } 

        private void EnableDeviceControls()
        {
            //获取扫描状态
            bool enable =IsConnected;

            button_initRadar.Enabled = enable;
            button_camera.Enabled = enable;
            button_focus.Enabled = enable;
            button_redLinght.Enabled = enable;
            button_attenuator.Enabled = enable;
            button_controlPanel.Enabled = enable;
            button_findSphere.Enabled = enable;
            button_changeStatus.Enabled = enable;

            groupBox_devicePara.Enabled = enable;
            groupBox_featurePara.Enabled = enable;

            m_pbStart.Enabled = enable;
            //groupBox_devicePara.Enabled = true;
            //groupBox_featurePara.Enabled = true;
        }

        private void button_focus_Click(object sender, EventArgs e)
        {
            if (m_Radar != null)
            {
                m_Radar.AutoFocus();
            }
        }

        private void button_redLinght_Click(object sender, EventArgs e)
        {
            if (button_redLinght.Text == "指示激光开")
            {
                m_Radar.LightOn();
                button_redLinght.Text = "指示激光关";
            }
            else if (button_redLinght.Text == "指示激光关")
            {
                m_Radar.LightOff();
                button_redLinght.Text = "指示激光开";
            }
        }

        private void button_attenuator_Click(object sender, EventArgs e)
        {
            //if (button_attenuator.Text == "衰减器开")
            //{
            //    m_Radar.Attenuator_ON();
            //    button_attenuator.Text = "衰减器关";
            //}
            //else if (button_attenuator.Text == "衰减器关")
            //{
            //    m_Radar.Attenuator_OFF();
            //    button_attenuator.Text = "衰减器开";
            //}
            Task powerOnTask = new Task(() =>
            {
                m_Radar.PowerOff();
            });
            powerOnTask.Start();
        }

        private void button_clearPath_Click(object sender, EventArgs e)
        {
            m_path.Clear();
            m_Radar.m_Path.Clear();
        }

        private void button_path_Click(object sender, EventArgs e)
        {
            double xstep = Convert.ToDouble(this.textBox_xstep.Text);
            double ystep = Convert.ToDouble(this.textBox_ystep.Text);
            double angle = Convert.ToDouble(this.textBox_direction.Text);
            int type = comboBox_method.SelectedIndex;
            GeneratePathPoints(xstep, ystep,angle,type);
            //StreamWriter sw = new StreamWriter("c:\\path.txt");
            //foreach (var p in m_receiver.m_stub.m_Radar.m_Path)
            //{
            //    sw.WriteLine(p.x + "," + p.y + ",0");
            //}
            //sw.Close();
        }
        private void GeneratePathPoints(double xstep, double ystep, double angle,int type)
        {
           
            switch (type)
            {
                //区域扫描
                case 0:
                    if (m_path.Count <= 1)
                    {
                        MessageBox.Show("控制点数量小于1，请添加控制点");
                    }
                    else
                    {
                        m_Radar.m_Path = m_Radar.generateRectangleScanPath(ystep, m_path);

                    }
                    break;
                //单点扫描
                case 1:
                    //m_receiver.m_stub.m_Radar.StopScan();
                    break;
                //多边形扫描
                case 2:
                    if (m_path.Count <= 3)
                    {
                        MessageBox.Show("控制点数量小于3，请添加控制点");
                    }
                    else
                    {
                        m_Radar.m_Path = m_Radar.generatePolygonScanPath(0, ystep, angle, m_path);
                    }
                    break;
                //测孔扫描
                case 3:

                    break;
                default:
                    return;
            }

            //MessageBox.Show("控制点数量：" + m_receiver.m_stub.m_Radar.m_Path.Count);
        }
        private void button_read_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                ReadPath(ofd.FileName);
            }
        }
        public void ReadPath(string filename)
        {
            m_path.Clear();
            FileStream fs = null;
            StreamReader sr = null;
            double[] xyz = new double[3];
            int cnt = 0;
            string sLineBuffer;
            string[] sABR;
            fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            sr = new StreamReader(fs);
            while (!sr.EndOfStream)
            {
                sLineBuffer = sr.ReadLine();
                cnt++;
                sABR = sLineBuffer.Split(chDelimiter, StringSplitOptions.RemoveEmptyEntries);
                if (sABR == null)
                {
                    MessageBox.Show("数据出错");
                }
                try
                {
                    xyz[0] = Convert.ToDouble(sABR[0]);
                    xyz[1] = Convert.ToDouble(sABR[1]);
                    //xyz[2] = Convert.ToDouble(sABR[2]);
                    m_path.Add(new pathPoint(xyz[0], xyz[1]));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                    continue;
                }
            }
        }

        private void button_findSphere_Click(object sender, EventArgs e)
        {
            Form_FindSphere2 m_FindSphere = new Form_FindSphere2(m_Radar);
            System.Windows.Forms.IWin32Window owner = null;
            m_FindSphere.Show(owner);
        }

        private void button_changeStatus_Click(object sender, EventArgs e)
        {          
            Task powerOnTask = new Task(() =>
            {
                m_Radar.PowerOn();
            });
            powerOnTask.Start();         
        }

        private void comboBox_featureMethod_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox_featureMethod.SelectedIndex == 0)
            {
                textBox_turns.Visible = false;
                label21.Visible = false;
            }
            else
            {
                textBox_turns.Visible = true;
                label21.Visible = true;
            }
        }    

        private void button1_Click(object sender, EventArgs e)
        {
            var pos = m_Radar.GetOneData();
            if (!m_Radar.SetCurrentPos(pos.a, pos.b))
            {
                MessageBox.Show("设置当前位置出现错误");
                return;
            }
            System.Threading.Thread.Sleep(50);
            double speed = Convert.ToDouble(this.textBox_ScanSpeed.Text);
            m_Radar.SetPolygonScanSpeed(speed);

        }

        private void button3_Click(object sender, EventArgs e)
        {
            m_Radar.PolygonScanStart();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (this.button4.Text == "暂停")
            {
                m_Radar.PolygonScanPause();
                this.button4.Text = "恢复";
            }
            else 
            {
                m_Radar.PolygonScanContinue();
                this.button4.Text = "暂停";
            }

        }
        private void button9_Click(object sender, EventArgs e)
        {
            m_Radar.PolygonScanEnd();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //m_receiver.m_stub.m_Radar.m_Path = m_path;
            m_Radar.ScanAddPoints(); 
        }

        private void button5_Click(object sender, EventArgs e)
        {
            //m_host.ExecuteCommand("TREEVIEW OBJECT SELECT NONE", true, true, false);
            //m_host.ExecuteCommand("TREEVIEW FEATURE MEASURED SELECT ( 1, \"On\" )", true, true, false);
            //m_host.ObtainSphereCenter("球1");
            //m_host.ExecuteCommand("TREEVIEW OBJECT SELECT NONE", true, true, false);
            //m_host.ObtainPoint("点 1");
           // m_host.ObtainFeaturePoints();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (m_Radar != null)
            {
                Form_LaserPosition m_ShowLaserPosition = new Form_LaserPosition(m_Radar);
                System.Windows.Forms.IWin32Window owner = null;
                m_ShowLaserPosition.Show(owner);
            }
            else
            {
                MessageBox.Show("请先连接雷达");
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            //m_host.ExecuteCommand("TREEVIEW OBJECT SELECT NONE", true, true, false);
            //m_host.ObtainSphereCenter("球 1");
        }

        private void button_add_Click(object sender, EventArgs e)
        {
            var pos = m_Radar.GetOneData();
            m_path.Add(new pathPoint(pos.a,pos.b));
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {

        }

        private void button_savePath_Click(object sender, EventArgs e)
        {

            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "(*.txt)|*.txt";
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {             
                Task saveTask = new Task(() =>
                {
                    if (m_path.Count > 0)
                    {
                        StreamWriter sw = new StreamWriter(saveDialog.FileName);
                        for (int i = 0; i < m_path.Count; i++)
                        {
                            sw.WriteLine(m_path[i].x + "," + m_path[i].y);
                        }
                        sw.Close();
                    }
                  
                    MessageBox.Show("保存文件至：" + saveDialog.FileName);
                });
                saveTask.Start();

            }
           
        }
        private void CreateCircleFormCloud()
        {
            //double[] input = m_receiver.m_stub.m_ScanData.ToArray();
            //double[] center = new double[3];
            //double[] radius = new double[1] { 0 }; ;
            //double[] normal = new double[3];
            //double[] sigma = new double[1] { 20 };
            //circle_compute(m_receiver.m_stub.m_ScanData.Count / 3, input, sigma, center, radius, normal);
            //CreateCircle(center[0], center[1], center[2], normal[0], normal[1], normal[2], radius[0] / 2);
        }

        private void CreateCircle(double x = 0,
        double y = 0,
        double z = 0,
        double i = 0,
        double j = 0,
        double k = 1,
        double r = 3)
        {
            try
            {                
                string pointPara = String.Format("{0},{1},{2},{3},{4},{5},{6}", x, y, z, i,j,k,r);             
                //m_host.ExecuteCommand(IM.Utils.CommandBuild("FEATURE PRIMITIVE CIRCLE CREATE", pointPara), true, false, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        static List<double> m_data = new List<double>();
        private void button11_Click(object sender, EventArgs e)
        {
            try
            {
                readCloud("C:\\Users\\LENOVO\\Desktop\\1111.txt");
                double[] input = m_data.ToArray();
                double[] center = new double[3];
                double[] radius = new double[1] { 0 }; ;
                double[] normal = new double[3];
                double[] sigma = new double[1] { 20 };
                circle_compute(m_data.Count / 3, input, sigma, center, radius, normal);
                CreateCircle(center[0], center[1], center[2], normal[0], normal[1], normal[2], radius[0]/2);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public static void readCloud(string filename)
        {
            FileInfo myFile = new FileInfo(filename);
            string name = myFile.Name;
            FileStream fs = null;
            StreamReader sr = null;
            double[] xyz = new double[3];

            char[] chDelimiter = new char[] { ' ', '\t', ';', ',' };
            int cnt = 0;
            string sLineBuffer;
            string[] sXYZ;
            fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            sr = new StreamReader(fs);
            while (!sr.EndOfStream)
            {
                sLineBuffer = sr.ReadLine();
                cnt++;
                sXYZ = sLineBuffer.Split(chDelimiter, StringSplitOptions.RemoveEmptyEntries);
                if (sXYZ == null)
                {
                    MessageBox.Show("数据出错");
                    return;
                }
                xyz[0] = Convert.ToDouble(sXYZ[0]);
                xyz[1] = Convert.ToDouble(sXYZ[1]);
                xyz[2] = Convert.ToDouble(sXYZ[2]);
                m_data.Add(xyz[0]);
                m_data.Add(xyz[1]);
                m_data.Add(xyz[2]);
            }
        }
        //Form_AGV m_AGV;
        private void button7_Click(object sender, EventArgs e)
        {
            //m_AGV = new Form_AGV(m_receiver.m_stub.m_Radar);
            //m_AGV.MdiParent = this;
           //m_AGV.SendAGVCmd += new AGVCmdCallback(ReceiveAGVCmd);
            Process[] procs = Process.GetProcessesByName("iminspect");
            IntPtr mainHwnd;
            foreach (var p in procs)
            {
                if (p.Id != 0)
                {

                    IntPtr hwnd = new IntPtr(0);
                    IntPtr EdithWnd = new IntPtr(0);

                    //从指定的主窗体查找子窗体
                    //IntPtr childHwnd = FindWindowEx(hwnd, EdithWnd, null, "Scan");

                    ///从所有桌面的窗体中查找FindWindowEx（0,0,null,name）;
                    IntPtr childHwnd = FindWindowEx(hwnd, EdithWnd, null, "扫描");
                    mainHwnd = childHwnd;
                    StringBuilder name = new StringBuilder();
                    GetWindowText(childHwnd, name, 100);
                    RECT_INFO rect = new RECT_INFO();
                    GetWindowRect(childHwnd, ref rect);
                   // m_AGV.Left = rect.Right;
                  //  m_AGV.Top = rect.Top;
                }
            }
            System.Windows.Forms.IWin32Window owner = null;
           // m_AGV.Show(owner);
        }
        public void ReceiveAGVCmd(string cmd,int type, string path,double xstep,double ystep,double angle,double speed)
        {
            //string[] paras = cmd.Split(',');
            //int  scanType = Convert.ToInt32( paras[1]);
            //string scanPath = paras[2];
            //double xstep = Convert.ToDouble(paras[3]);
            //double ystep = Convert.ToDouble(paras[4]);
            //double angle = Convert.ToDouble(paras[5]);
            //double speed = Convert.ToDouble(paras[6]);
            ReadPath(path);
            this.Invoke(new EventHandler(delegate
            {
                comboBox_method.SelectedIndex = type;
                m_cbSurface.SelectedIndex = 0;
            }));

            GeneratePathPoints(xstep, ystep, angle, type);
            pbStartClick(new object(), new EventArgs());
            Debug.WriteLine("开始扫描");
            //var thread5 = new System.Threading.Thread(new System.Threading.ThreadStart(
            //    () =>
            //    {
            //        ReadPath(path);
            //        this.Invoke(new EventHandler(delegate
            //        {
            //            comboBox_method.SelectedIndex = type;
            //        }));
                    
            //        GeneratePathPoints(xstep, ystep, angle, type);
            //        pbStartClick(new object(), new EventArgs());
            //    }
            //        ));
            //thread5.SetApartmentState(System.Threading.ApartmentState.STA);
            //thread5.Start();
            //Task scanTask = new Task(() =>
            //{
            //    ReadPath(path);
            //    comboBox_method.SelectedIndex = type;
            //    GeneratePathPoints(xstep, ystep, angle, type);
            //    pbStartClick(new object(), new EventArgs());
            //});
            //scanTask.Start();
        }

        private void button_readFromPw_Click(object sender, EventArgs e)
        {
            //Form_GetDataFromPw m_PwForm = new Form_GetDataFromPw(m_host);
            //Process[] procs = Process.GetProcessesByName("iminspect");
            //IntPtr mainHwnd;
            //foreach (var p in procs)
            //{
            //    if (p.Id != 0)
            //    {
            //        IntPtr hwnd = new IntPtr(0);
            //        IntPtr EdithWnd = new IntPtr(0);
            //        IntPtr childHwnd = FindWindowEx(hwnd, EdithWnd, null, "扫描");
            //        mainHwnd = childHwnd;
            //        StringBuilder name = new StringBuilder();
            //        GetWindowText(childHwnd, name, 100);
            //        RECT_INFO rect = new RECT_INFO();
            //        GetWindowRect(childHwnd, ref rect);
            //        m_PwForm.Left = rect.Right;
            //        m_PwForm.Top = rect.Top;
            //    }
            //}
            //System.Windows.Forms.IWin32Window owner = null;
            //m_PwForm.Show(owner);
        }

        private void button15_Click(object sender, EventArgs e)
        {
            if (m_Radar == null)
            {
               m_Radar = new DeviceRadar();
            }
            Form_Parameters m_Parameters = new Form_Parameters(m_Radar);
            System.Windows.Forms.IWin32Window owner = null;
            m_Parameters.Show(owner);
        }

        private void button17_Click(object sender, EventArgs e)
        {
            if (m_Radar != null)
            {
                m_Radar.FocusHome();
            }
        }

        private void button18_Click(object sender, EventArgs e)
        {
            if (m_Radar != null)
            {
                m_Radar.SetZero();
            }
        }

        private void button19_Click(object sender, EventArgs e)
        {
            Int64 pos = Convert.ToInt64(this.textBox_focus_pos.Text);
            Int64 speed = Convert.ToInt64(this.textBox_focus_speed.Text);
            if (m_Radar != null)
            {
                m_Radar.FocusMoveTo(speed,pos);
            }
        }

        private void button20_MouseDown(object sender, MouseEventArgs e)
        {
            Int64 speed = Convert.ToInt64(this.textBox_focus_speed.Text);
            if (m_Radar != null)
            {
                m_Radar.FocusMovePos(speed);
            }
        }

        private void button20_MouseUp(object sender, MouseEventArgs e)
        {
            if (m_Radar != null)
            {
                m_Radar.FocusStop();
            }
        }

        private void button21_MouseDown(object sender, MouseEventArgs e)
        {
            Int64 speed = Convert.ToInt64(this.textBox_focus_speed.Text);
            if (m_Radar != null)
            {
                m_Radar.FocusMoveNeg(speed);
            }
        }

        private void button21_MouseUp(object sender, MouseEventArgs e)
        {
            if (m_Radar != null)
            {
                m_Radar.FocusStop();
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {

        }

        private void button22_Click(object sender, EventArgs e)
        {
            string stop1 = this.textBox_BandStop1.Text;
            string stop2 = this.textBox_BandStop2.Text;
            if (m_Radar != null)
            {
                m_Radar.SetBandStop(stop1, stop2);
            }
        }



        //public void ReceivedScanMeasureCallBack(double x, double y, double z)
        //{
        //    //MeasFeatures.Get_Instance().Get_Feature(this.curPtsKey).ActualPoints.Add(new BasePoint(x,y,z));
        //    MeasFeatures.Get_Instance().Get_FeatPointCloud(this.curPtsKey).cloudPoints.Add(new BasePoint(x, y, z));
        //    this.MdiParent.m_viewFrom.AddPoints(x, y, z);
        //    if (this.m_polyworks != null)
        //    {
        //        this.m_polyworks.AddPoint(x, y, z);
        //    }
        //}
    }

}
